package com.skyun.watchmanager;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.skyun.watchserer.common.models.AppInfo;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by skyun on 17/8/22.
 */
public class AppAdapter extends ArrayAdapter<AppInfo> {

    private Map<String, Drawable> mIcons = new HashMap<>();

    public AppAdapter(Context context) {
        super(context, 0);
    }

    public void addAllIcons(Map<String, Drawable> icons) {
        mIcons.putAll(icons);
    }

    public void addIcon(String packName, Bitmap icon) {
        Drawable drawable = new BitmapDrawable(getContext().getResources(), icon);
        mIcons.put(packName, drawable);
    }

    public Map<String, Drawable> getIcons() {
        return mIcons;
    }

    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(getContext(), R.layout.item_app, null);
            holder = new ViewHolder();
            holder.iconView = (ImageView) convertView.findViewById(R.id.app_iv_icon);
            holder.nameView = (TextView) convertView.findViewById(R.id.app_tv_name);
            holder.versionView = (TextView) convertView.findViewById(R.id.app_tv_version_name);
            holder.packView = (TextView) convertView.findViewById(R.id.app_tv_pack_name);
            holder.installTime = (TextView) convertView.findViewById(R.id.app_tv_install_time);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        AppInfo appInfo = getItem(position);
        holder.nameView.setText(appInfo.name);
        if (mIcons.get(appInfo.packageName) != null) {
            holder.iconView.setImageDrawable(mIcons.get(appInfo.packageName));
        } else {
            holder.iconView.setImageDrawable(null);
        }
//        holder.packView.setText(appInfo.packageName);
//        holder.versionView.setText(appInfo.version);
//        holder.installTime.setText(appInfo.getInstallTime());

        return convertView;
    }

    public static class ViewHolder {
        public ImageView iconView;
        public TextView nameView;
        public TextView packView;
        public TextView versionView;
        public TextView installTime;
    }
}
